package com.DosonLeung.homeschoolcommunication.Components;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.DosonLeung.homeschoolcommunication.Constant.UserConstant;
import com.DosonLeung.homeschoolcommunication.Controllers.ReadActivity;
import com.DosonLeung.homeschoolcommunication.Models.ChatModel;
import com.DosonLeung.homeschoolcommunication.R;
import com.DosonLeung.homeschoolcommunication.SQLite.MembersDB;
import com.DosonLeung.homeschoolcommunication.Utils.AlbumUtil;
import com.DosonLeung.homeschoolcommunication.Utils.ImageUtil;
import com.DosonLeung.homeschoolcommunication.Utils.RecordUtil;
import com.DosonLeung.homeschoolcommunication.Utils.StorageUtil;
import com.DosonLeung.homeschoolcommunication.Utils.TimeUtil;
import com.DosonLeung.homeschoolcommunication.Views.ChatItem;
import com.DosonLeung.homeschoolcommunication.Views.ChatLayout;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by DosonLeung on 2014/10/22.
 */

public class TestAdapter{
    private ChatModel chatModel;
    private int[] mTo;
    private String[] mFrom;

    private List<Map<String, String>> mData;
    private ArrayList<String> chatIDs;
    private int size;

    private int mResource;
    private int mTargetResouce;
    private int mSelfResouce;
    private int[] mlid;
    private int[] mrid;
    private ChatLayout container;

    private Handler handler;//来自chatActivity的Handler
    private String avatar_path;
    private String quality = "30";
    private Bitmap bitmap;
    private ArrayList<ImageView> imageList = new ArrayList<ImageView>();
    private ArrayList<HashMap<String, Object>> bitmapList = new ArrayList<HashMap<String, Object>>();
    private ArrayList<ImageView> mumList = new ArrayList<ImageView>();//菊花链，仅用于上传,失败后被回调

    public TestAdapter(ChatModel chatModel,ChatLayout container,List<? extends Map<String, ?>> data,String avatar_path,int targetResource,
                       int selfResouce,String[] from, int[] lid,int[] rid,Handler handler) {
        this.chatModel = chatModel;
        this.container = container;
        this.avatar_path = avatar_path;
        this.handler = handler;
        mData = (List<Map<String, String>>) data;
        mResource = targetResource;
        mTargetResouce = targetResource;
        mSelfResouce = selfResouce;
        mFrom = from;
        mTo = lid;
        mlid = lid;
        mrid = rid;
    }

    public void init(){
        ChatItem v;
        size = mData.size();
        if(chatIDs==null)
            chatIDs = new ArrayList<String>();
        for(int i = 0;i < size;i ++){
           v = getView(i,null,container);
           container.addView(v);
           chatIDs.add(i,v.getChatId());
        }
        container.smoothScrollToButtom();
    }

    public ArrayList<ImageView> getImageList() {
        return imageList;
    }

    public ArrayList<HashMap<String, Object>> getBitmapList() {
        return bitmapList;
    }

    public ArrayList<ImageView> getMumList() {
        return mumList;
    }

    public int getCount(){
        return size;
    }

    private ChatItem getView(int position, View convertView, ViewGroup parent) {
        Object uidObject = mData.get(position).get("uid");//如果是班级信息
        try {
            if (uidObject instanceof String) {
                String uid = (String) uidObject;
                if ((uid).equalsIgnoreCase(UserConstant.USER_ID)) {
                    mResource = mSelfResouce;
                } else {
                    mResource = mTargetResouce;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return createViewFromResource(position, convertView, parent, mResource);
    }

    private ChatItem createViewFromResource(int position, View convertView,
                                        ViewGroup parent, int resource) {
        final ChatItem v;
        String target;
        if (convertView == null) {
            v = (ChatItem) chatModel.getApp().getLayoutInflater().inflate(resource, parent, false);
        } else {
            v = (ChatItem) convertView;
        }
        target = bindView(position, v);
        if(UserConstant.USER_CHARACTER.equals("teacher")&&chatModel.getType()){
            if(!target.equals(UserConstant.USER_ID)){
                v.setVisibility(View.GONE);
            }
            else {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int position = getPositionById(v.getChatId());
                        setOnItemClickListener(chatModel.getApp(), chatModel.getTarget(), getTimeByPosition(position));
                    }
                });
            }
        }
        return v;
    }


    private String bindView(final int position, View view) {
        final Map dataSet = mData.get(position);
        //Log.e("Fuck this ChatActivity : ", dataSet.toString());
        final String target = (String) (dataSet.get("uid"));
        final String contentType = (String) (dataSet.get("contentType"));
        final String contentLevel = (String) (dataSet.get("contentLevel"));
        final String[] from = mFrom;
        final boolean role;//false为对方，true为我
        ImageView mum;
        ImageView icon_background;
        if (target.equalsIgnoreCase(UserConstant.USER_ID)) {
            mTo = mrid;
            role = true;
            mum = (ImageView) view.findViewById(R.id.r_wait);
            icon_background = (ImageView) view.findViewById(R.id.r_icon_background);
            if(contentLevel.equals("1")){
                icon_background.setImageResource(R.drawable.chat_list_mine_important);
            }else if(contentLevel.equals("2")){
                icon_background.setImageResource(R.drawable.chat_list_mine_ordinary);
            }else if(contentLevel.equals("3")){
                icon_background.setImageResource(R.drawable.chat_list_mine_routine);
            }
        } else {
            mTo = mlid;
            role = false;
            mum = (ImageView) view.findViewById(R.id.l_wait);
            icon_background = (ImageView) view.findViewById(R.id.l_icon_background);
            if(contentLevel.equals("1")){
                icon_background.setImageResource(R.drawable.chat_list_other_important);
            }else if(contentLevel.equals("2")){
                icon_background.setImageResource(R.drawable.chat_list_other_ordinary);
            }else if(contentLevel.equals("3")){
                icon_background.setImageResource(R.drawable.chat_list_other_routine);
            }
        }

        final int[] to = mTo;
        final int count = to.length;
        for (int i = 0; i < count; i++) {
            final View v = view.findViewById(to[i]);
            if (v != null) {
                final Object data = dataSet.get(from[i]);
                String text = data == null ? "" : data.toString();
                if (text == null) {
                    text = "";
                }
                //这里判断可选项
                mum.setVisibility(View.GONE);
                //这里判断声音文件
                if (v instanceof Button) {
                    if (contentType.equalsIgnoreCase("audio")) {
                        if(role) {//为我方
                            if (data instanceof Integer) {
                                ((Button) v).setText("错误格式音频");
                            } else {
                                final MediaPlayer voicePlayer = null;
                                final String url = text;
                                if(url.equals("")) {//非音频
                                    v.setVisibility(View.GONE);
                                }else if(url.contains("http://jiaxiaotong.qiniudn.com")){//上传成功
                                    final String address = StorageUtil.getVoiceDir()+url.replace("http://jiaxiaotong.qiniudn.com","");
                                    try {
                                        v.setVisibility(View.VISIBLE);
                                        ((Button) v).setText(" ["+((int)(RecordUtil.getMediaDuration(voicePlayer, url)))/1000+"秒"+"] ");
                                        //请求service上传音频
                                        if(contentLevel.equals("1")){
                                            v.setBackgroundResource(R.drawable.rounded_important);
                                        }else if(contentLevel.equals("2")){
                                            v.setBackgroundResource(R.drawable.rounded_ordinary);
                                        }else if(contentLevel.equals("3")){
                                            v.setBackgroundResource(R.drawable.rounded_routine);
                                        }
                                        v.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                try {
                                                    RecordUtil.playVoice(voicePlayer, address);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        });
                                        mum.setVisibility(View.GONE);
                                    } catch (OutOfMemoryError e) {
                                        e.printStackTrace();
                                    }
                                } else {//上传失败
                                    try {
                                        v.setVisibility(View.VISIBLE);
                                        ((Button) v).setText(" ["+((int)(RecordUtil.getMediaDuration(voicePlayer, url)))/1000+"秒"+"] ");
                                        //请求service上传音频
                                        if(contentLevel.equals("1")){
                                            v.setBackgroundResource(R.drawable.rounded_important);
                                        }else if(contentLevel.equals("2")){
                                            v.setBackgroundResource(R.drawable.rounded_ordinary);
                                        }else if(contentLevel.equals("3")){
                                            v.setBackgroundResource(R.drawable.rounded_routine);
                                        }
                                        v.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                try {
                                                    RecordUtil.playVoice(voicePlayer, url);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        });
                                        mum.setVisibility(View.VISIBLE);
                                    } catch (OutOfMemoryError e) {
                                        e.printStackTrace();
                                    }
                                }

                            }
                        }else{//为对方，对方发送音频只有在已经接收后才显示
                            if (data instanceof Integer) {
                                ((Button) v).setText("错误格式音频");
                            } else {
                                final MediaPlayer voicePlayer = null;
                                final String url = text;
                                File voice = new File(url);
                                if (!voice.exists()) {
                                    if(!url.equals("")) {//文件不存在，路径依然为下载链接
                                        v.setVisibility(View.VISIBLE);
                                        ((Button) v).setText("下载失败");
                                        if(contentLevel.equals("1")){
                                            v.setBackgroundResource(R.drawable.rounded_important);
                                        }else if(contentLevel.equals("2")){
                                            v.setBackgroundResource(R.drawable.rounded_ordinary);
                                        }else if(contentLevel.equals("3")){
                                            v.setBackgroundResource(R.drawable.rounded_routine);
                                        }
                                        mum.setImageResource(R.drawable.warning);
                                        mum.setVisibility(View.VISIBLE);
                                    }else{//文件不存在，路径为空，为其它消息
                                        v.setVisibility(View.GONE);
                                        mum.setVisibility(View.GONE);
                                    }
                                } else {
                                    v.setVisibility(View.VISIBLE);
                                    ((Button) v).setText(" [" + (int)(RecordUtil.getMediaDuration(voicePlayer,url)/1000) + "] ");
                                    if(contentLevel.equals("1")){
                                        v.setBackgroundResource(R.drawable.rounded_important);
                                    }else if(contentLevel.equals("2")){
                                        v.setBackgroundResource(R.drawable.rounded_ordinary);
                                    }else if(contentLevel.equals("3")){
                                        v.setBackgroundResource(R.drawable.rounded_routine);
                                    }
                                    v.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            try {
                                                RecordUtil.playVoice(voicePlayer, url);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    } else {
                        v.setVisibility(View.GONE);
                    }
                } else if (v instanceof TextView) {//文本部分
                    // Note: keep the instanceof TextView check at the bottom of these
                    // ifs since a lot of views are TextViews (e.g. CheckBoxes).
                    if(contentType.equals("image")||contentType.equals("audio")) {
                        if(v.getId()==R.id.chatlist_litem_text||v.getId()==R.id.chatlist_ritem_text)
                            v.setVisibility(View.GONE);
                        else
                            ((TextView) v).setText(TimeUtil.simplfyDate(text)+"  "+TimeUtil.simplifyTime(text));
                    }else {
                        if(v.getId()==R.id.chatlist_litem_time||v.getId()==R.id.chatlist_ritem_time)
                            ((TextView) v).setText(TimeUtil.simplfyDate(text)+"  "+TimeUtil.simplifyTime(text));
                        else {
                            if(contentLevel.equals("1")){
                                v.setBackgroundResource(R.drawable.rounded_important);
                            }else if(contentLevel.equals("2")){
                                v.setBackgroundResource(R.drawable.rounded_ordinary);
                            }else if(contentLevel.equals("3")){
                                v.setBackgroundResource(R.drawable.rounded_routine);
                            }
                            ((TextView) v).setText(text);
                        }
                    }
                } else if (v instanceof ImageView) {//图像部分
                    //这里判断头像
                    if (v.getId() == R.id.chatlist_litem_icon) {
                        Bitmap bitmap;
                        String length = (String)dataSet.get("length");//通过获取length来判断是否为班级信息
                        String sender_uid = (String)dataSet.get("extra");
                        if(!length.equals("")) {//为班级信息
                            MembersDB membersDB = new MembersDB(chatModel.getApp(), StorageUtil.getChatDir().toString() + "/" + "members.db3", 1);
                            String path = membersDB.getElementByUid("avatar_path",sender_uid.equals("")?target:sender_uid);
                            if(!path.equals(""))
                                avatar_path = path;
                        }
                        final String imageName = avatar_path.substring(avatar_path.lastIndexOf("/") + 1, avatar_path.lastIndexOf(".")) + ".png";
                        if (StorageUtil.fileExists("/" + "camera" + "/" + imageName)) {
                            //从本地提取
                            try {
                                bitmap = BitmapFactory.decodeFile(StorageUtil.getCameraDir() + "/" + imageName);
                                ((ImageView) v).setImageBitmap(bitmap);
                            } catch (OutOfMemoryError e) {
                                e.printStackTrace();
                            }
                            v.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    AlbumUtil.openInAlbum(chatModel.getApp(), StorageUtil.getCameraDir() + "/" + imageName);
                                }
                            });
                        } else {
                            //不存在该文件
                            ((ImageView) v).setImageResource(R.drawable.icon_loading);
                        }

                    } else if (v.getId() == R.id.chatlist_ritem_icon) {
                        ImageUtil.getMyIcon((ImageView) v);
                    }//这里判断图片内容
                    else if (role) {//为我方
                        if (contentType.equalsIgnoreCase("image")) {
                            final String url = text;
                            final String address;
                            Bitmap bitmap;
                            //Log.e("Album", "Position = "+position + " url = " + url);
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeFile(url, options);
                            options.inSampleSize = ImageUtil.computeSampleSize(options, -1, 128 * 128);
                            options.inJustDecodeBounds = false;
                            if(url.equals("")) {//非图片类型
                                v.setVisibility(View.GONE);
                            }else if(url.contains("http://jiaxiaotong.qiniudn.com")){//上传成功
                                address = StorageUtil.getCameraDir()+url.replace("http://jiaxiaotong.qiniudn.com","");
                                try {
                                    bitmap = BitmapFactory.decodeFile(address, options);
                                    if(chatModel.photo)
                                        bitmap = ImageUtil.adjustBitmapRotation(bitmap,90);
                                    if(v.getId()==R.id.chatlist_litem_image||v.getId()==R.id.chatlist_ritem_image){
                                        ((ImageView) v).setImageBitmap(bitmap);
                                        if(contentLevel.equals("1")){
                                            v.setBackgroundResource(R.drawable.rounded_important);
                                        }else if(contentLevel.equals("2")){
                                            v.setBackgroundResource(R.drawable.rounded_ordinary);
                                        }else if(contentLevel.equals("3")){
                                            v.setBackgroundResource(R.drawable.rounded_routine);
                                        }
                                        v.setVisibility(View.VISIBLE);
                                    }
                                    mum.setVisibility(View.GONE);
                                } catch (OutOfMemoryError e) {
                                    e.printStackTrace();
                                }
                                v.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        AlbumUtil.openInAlbum(chatModel.getApp(),address);
                                    }
                                });
                            } else {//上传中
                                try {
                                    bitmap = BitmapFactory.decodeFile(url, options);
                                    if(chatModel.photo)
                                        bitmap = ImageUtil.adjustBitmapRotation(bitmap,90);
                                    if(v.getId()==R.id.chatlist_litem_image||v.getId()==R.id.chatlist_ritem_image){
                                        ((ImageView) v).setImageBitmap(bitmap);
                                        v.setVisibility(View.VISIBLE);
                                        if(contentLevel.equals("1")){
                                            v.setBackgroundResource(R.drawable.rounded_important);
                                        }else if(contentLevel.equals("2")){
                                            v.setBackgroundResource(R.drawable.rounded_ordinary);
                                        }else if(contentLevel.equals("3")){
                                            v.setBackgroundResource(R.drawable.rounded_routine);
                                        }
                                        v.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                AlbumUtil.openInAlbum(chatModel.getApp(),url);
                                            }
                                        });
                                    }
                                    mum.setVisibility(View.GONE);
                                } catch (OutOfMemoryError e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {//这里是对方的图片
                        if (contentType.equals("image")) {
                            final String address = text;
                            String names;
                            try {
                                names = address.substring(address.lastIndexOf("/") + 1, address.lastIndexOf(".")) + ".png";
                            }catch (StringIndexOutOfBoundsException e){
                                e.printStackTrace();
                                names = address;
                            }
                            final String imageName = names;
                            final String link = text + "?imageMogr2/quality/" + quality;
                            Log.e("link = ", link);
                            imageList.add((ImageView) v);
                            final Integer size = imageList.size() - 1;
                            if (StorageUtil.fileExists("/" + "camera" + "/" + imageName)) {
                                //优先从本地提取
                                try {
                                    bitmap = BitmapFactory.decodeFile(StorageUtil.getCameraDir() + "/" + imageName);
                                } catch (OutOfMemoryError e) {
                                    e.printStackTrace();
                                }
                                if(v.getId()==R.id.chatlist_litem_image||v.getId()==R.id.chatlist_ritem_image){
                                    ((ImageView) v).setImageBitmap(bitmap);
                                    v.setVisibility(View.VISIBLE);
                                    if(contentLevel.equals("1")){
                                        v.setBackgroundResource(R.drawable.rounded_important);
                                    }else if(contentLevel.equals("2")){
                                        v.setBackgroundResource(R.drawable.rounded_ordinary);
                                    }else if(contentLevel.equals("3")){
                                        v.setBackgroundResource(R.drawable.rounded_routine);
                                    }
                                    v.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            AlbumUtil.openInAlbum(chatModel.getApp(),address);
                                        }
                                    });
                                }
                            } else {
                                //本地无法找不到文件,从网络提取
                                new Thread() {
                                    public void run() {
                                        Integer index = size;
                                        try {
                                            HashMap<String, Object> item = new HashMap<String, Object>();
                                            URL url = new URL(link);
                                            InputStream is = url.openStream();
                                            BitmapFactory.Options options = new BitmapFactory.Options();
                                            options.inJustDecodeBounds = false;
                                            int imageHeight = options.outHeight;
                                            int imageWidth = options.outWidth;
                                            int s = imageHeight * imageWidth;
                                            if (s > 10000) {
                                                options.inSampleSize = s / 20;
                                            } else {
                                                options.inSampleSize = 2;
                                            }
                                            try {
                                                bitmap = BitmapFactory.decodeStream(is, null, options);
                                            } catch (OutOfMemoryError e) {
                                                e.printStackTrace();
                                            }
                                            item.put("index", index);
                                            item.put("name", imageName);
                                            item.put("bitmap", bitmap);
                                            item.put("url",StorageUtil.getCameraDir().toString()+"/"+imageName);
                                            StorageUtil.saveAsImage(imageName, bitmap);
                                            bitmapList.add(item);
                                            handler.sendEmptyMessage(0x202);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }.start();
                                if(contentLevel.equals("1")){
                                    v.setBackgroundResource(R.drawable.rounded_important);
                                }else if(contentLevel.equals("2")){
                                    v.setBackgroundResource(R.drawable.rounded_ordinary);
                                }else if(contentLevel.equals("3")){
                                    v.setBackgroundResource(R.drawable.rounded_routine);
                                }
                                ((ImageView) v).setImageResource(R.drawable.icon_loading);
                                v.setVisibility(View.VISIBLE);
                                v.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        reloadImage(size,link,imageName).start();
                                    }
                                });
                            }
                        }
                    }
                } else {
                    throw new IllegalStateException(v.getClass().getName() + " is not a " +
                            " view that can be bounds by this SimpleAdapter");
                }
            }
        }
        return target;
    }

    private Thread reloadImage(final int size,final String link,final String imageName){
        //本地无法找不到文件,从网络提取
        return new Thread() {
            public void run() {
                Integer index = size;
                try {
                    HashMap<String, Object> item = new HashMap<String, Object>();
                    URL url = new URL(link);
                    InputStream is = url.openStream();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = false;
                    int imageHeight = options.outHeight;
                    int imageWidth = options.outWidth;
                    int s = imageHeight * imageWidth;
                    if (s > 10000) {
                        options.inSampleSize = s / 20;
                    } else {
                        options.inSampleSize = 2;
                    }
                    try {
                        bitmap = BitmapFactory.decodeStream(is, null, options);
                    } catch (OutOfMemoryError e) {
                        e.printStackTrace();
                    }
                    item.put("index", index);
                    item.put("name", imageName);
                    item.put("bitmap", bitmap);
                    item.put("url",StorageUtil.getCameraDir().toString()+"/"+imageName);
                    StorageUtil.saveAsImage(imageName, bitmap);
                    bitmapList.add(item);
                    handler.sendEmptyMessage(0x202);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    public void notifyDataSetChanged(){
        int newSize = mData.size();
        ChatItem chatItem;
        while(size < newSize){
            chatItem = getView(size,null,container);
            container.addView(chatItem);
            chatIDs.add(size,chatItem.getChatId());
            size++;
        }
        container.smoothScrollToButtom();
    }

    public void setOnItemClickListener(Activity app,String target,String time){
        startReadActivity(app, target, time);
    }

    private void startReadActivity(Activity app,String target,String time){
        Intent intent = new Intent(app, ReadActivity.class);
        intent.putExtra("cid", target);
        intent.putExtra("time", time);
        app.startActivity(intent);
    }

    private String getTimeByPosition(int position){
        Date date;
        String interval = "";
        Map<String,String> item;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            item = chatModel.chatList.get(position);
            date = sdf.parse(TimeUtil.standardTime(item.get("time")));
            interval = String.valueOf(date.getTime()/1000);
        }catch (Exception e){
            e.printStackTrace();
        }
        return interval;
    }

    public int getPositionById(String chatId){
        int i = -1;
        for(i = 0;i < size;i++){
            if(chatIDs.get(i).equals(chatId))
            break;
        }
        return i;
    }

    public void addNotesAtFirst(LinkedList<Map<String,String>> list){
        int notesSize = list.size();
        Map<String,String> item;
        ChatItem chatItem;
        try {
            for (int i = notesSize; i > 0; i--) {
                item = list.get(i-1);
                chatModel.chatList.add(0,item);//这里等价于mData.add(0,item)
                chatItem = getView(0,null,container);
                container.addView(chatItem,0);
                chatIDs.add(0,chatItem.getChatId());
                size++;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}


